import { defineStore } from 'pinia'
import { login, register, getUserInfo } from '@/services/auth'
import { ElMessage } from 'element-plus'
import router from "@/router/index.js";

// 定义用户 store
export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: {
        id: null,
        username: '',
        email: '',
        sex: '',
        birthday: '',
        introduction: '',
        picUrl: ''
    }
  }),

  getters: {
    isLoggedIn: (state) => !!state.token
  },

  actions: {
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    logout() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
        router.push('/shouye')
    },

    async doLogin(loginData) {
      try {
        const response = await login(loginData)
        if (response.code === '200') {
          this.setToken(response.data.token)
          this.userInfo = {
            id: response.data.id,
            username: response.data.username,
            email: response.data.email
          }
          return response
        } else {
          throw new Error(response.msg || '登录失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '登录失败')
        throw error
      }
    },

    async doRegister(registerData) {
      try {
        const response = await register(registerData)
        if (response.code === '1') {
          ElMessage.success('注册成功')
          return response
        } else {
          throw new Error(response.msg || '注册失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '注册失败')
        throw error
      }
    },

    async fetchUserInfo() {
      try {
        const response = await getUserInfo()
        if (response.code === '1') {
          this.userInfo = response.data
        } else {
          throw new Error(response.msg || '获取用户信息失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '获取用户信息失败')
        throw error
      }
    },
  }
})
